package com.yc.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yc.entity.ClassInfo;
import com.yc.entity.Schedule;
import com.yc.entity.StudentInfo;
import com.yc.entity.User;
import com.yc.exception.CustomException;
import com.yc.service.AttendanceService;
import com.yc.service.ScheduleService;
import com.yc.service.impl.ClassInfoServiceImpl;
import com.yc.service.impl.StudentInfoServiceImpl;
import com.yc.vo.Result;
import com.yc.vo.StudentAttendanceRecord;
import com.yc.vo.StudentEdit;
import com.yc.vo.StudentInfoAndClassInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 朱盼林
 * @version 1.0
 * @description:
 * @date 2023/6/29 19:24
 */
@Api("学生管理信息控制器")
@RestController
@RequestMapping("/student")
public class StudentInfoController {

    @Resource
    private StudentInfoServiceImpl studentInfoService;

    @Resource
    private ClassInfoServiceImpl classInfoService;

    @Resource
    private ScheduleService scheduleService;

    @Resource
    private AttendanceService attendanceService;


    /**
     * 查询学生信息
     * @param currentPage 当前页
     * @param pageSize  每页条数
     * @param studentEdit   查询学生信息
     * @return
     */
    @ApiOperation("分页查询+组合条件查询")
    @PostMapping(path = "/query/{pageNum}/{pageSize}")
    public Result pageQuery(@ApiParam(name = "currentPage", value = "当前页面", required = true)@PathVariable("pageNum") Integer currentPage,
                            @ApiParam(name = "pageSize", value = "每页查询页数", required = true)@PathVariable("pageSize") Integer pageSize,
                            @RequestBody StudentEdit studentEdit,
                            @SessionAttribute("user")User user){
        studentEdit.setUser(user);
        // 1.分页查询
        // 构建分页
        Page<StudentInfoAndClassInfo> page = new Page<>(currentPage, pageSize);
        Page<StudentInfoAndClassInfo> studentInfoAndClassInfoPage = studentInfoService.selectStudentInfoAndClassInfo(page, studentEdit);
        List<StudentInfoAndClassInfo> records = studentInfoAndClassInfoPage.getRecords();
        long total = studentInfoAndClassInfoPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("data", records);
        res.put("total", total);
        if (records != null && records.size() > 0){
            return Result.success(res);
        }else if (total == 0) {
            return Result.error("暂无信息!");
        }else {
            return Result.error("没有" + studentEdit.getCname() + "的信息!");
        }
    }

    /**
     * 添加学生
     * @param studentEdit 学生信息
     * @param userId    操作人id
     * @return
     */
    @ApiOperation("添加学生")
    @PostMapping("/add")
    public Result addStudent(@RequestBody StudentEdit studentEdit, @SessionAttribute("userID") Integer userId){
        ClassInfo classInfo = classInfoService.selectByCname(studentEdit.getCname());
        studentEdit.setCid(classInfo.getId());
        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setSname(studentEdit.getSname());
        studentInfo.setCid(studentEdit.getCid());
        studentInfo.setStuid(studentEdit.getStuid());
        studentInfo.setSphone(studentEdit.getSphone());
        studentInfo.setSsex(studentEdit.getSsex());
        studentInfo.setCreateBy(userId + "");
        studentInfo.setUpdateBy(userId + "");
        int result = studentInfoService.addStudent(studentInfo);
        if (result > 0){
            return Result.success("添加成功");
        }else {
            return Result.error("添加失败");
        }
    }

    /**
     * 修改学生信息
     * @param id    学生id
     * @param studentEdit   学生信息
     * @param userId    操作人id
     * @return
     */
    @ApiOperation("修改学生")
    @PutMapping("/modify/{id}")
    public Result modifyStudent(@ApiParam(value = "修改学生的id") @PathVariable("id") String id,
                                @RequestBody StudentEdit studentEdit,
                                @SessionAttribute("userID") Integer userId){
        ClassInfo classInfo = classInfoService.selectByCname(studentEdit.getCname());
        studentEdit.setCid(classInfo.getId());
        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setSname(studentEdit.getSname());
        studentInfo.setCid(studentEdit.getCid());
        studentInfo.setStuid(studentEdit.getStuid());
        studentInfo.setSphone(studentEdit.getSphone());
        studentInfo.setSsex(studentEdit.getSsex());
        studentInfo.setUpdateBy(userId + "");
        studentInfo.setId(studentEdit.getId());
        int result = studentInfoService.modifyStudent(studentInfo);
        if (result > 0){
            return Result.success("添加成功!");
        }else {
            return Result.error("添加失败,请联系管理员!");
        }
    }

    // 根据id删除学生
    @ApiOperation("删除学生")
    @DeleteMapping("/delete/{id}")
    public Result deleteStudent(@ApiParam(value = "被删除学生的id")@PathVariable("id") Integer id){
        boolean b = studentInfoService.deleteById(id);
        if (b){
            return Result.success("删除成功!");
        }else {
            return Result.error("删除失败,请联系管理员!");
        }
    }

    // 根据id批量删除学生
    @ApiOperation("批量删除学生")
    @PostMapping("/deletes")
    public Result deleteStudent(@RequestParam("ids") List<Integer> ids){
        int size = ids.size();
        int i;
        for (i = 0; i < size; ++i){
            studentInfoService.deleteById(ids.get(i));
        }
        if (i == size){
            return Result.success("批量删除成功!");
        }else {
            return Result.error("批量删除失败!");
        }
    }

    @ApiOperation("任命学生为班长，或学委, 或撤职")
    @PutMapping("/update/{id}/{cid}/{spare}")
    public Result appointStudent(@ApiParam(value = "被任命学生的id") @PathVariable("id") Integer id,
                                 @ApiParam(value = "被任命学生的班级") @PathVariable("cid") Integer cid,
                                 @ApiParam(value = "任命的职位") @PathVariable("spare") String spare){
        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setId(id);
        studentInfo.setCid(cid);
        studentInfo.setSpare(spare);
        int result = studentInfoService.appointStudent(studentInfo);
        if (result > 0){
            return Result.success("任命成功!");
        }else {
            return Result.error("任命失败!");
        }
    }

    @ApiOperation("下载模板文件")
    @GetMapping("/downLoadTemplate")
    public void downLoadTemplate(HttpServletResponse response) {
        Result result;
        try {
            studentInfoService.downloadTemplate(response);
            result = Result.success();
        } catch (IOException e) {
            e.printStackTrace();
            result = Result.error(e.getMessage());
        }
        //return result;
    }

    @ApiOperation("文件上传学生信息")
    @PostMapping("/file/upload")
    public Result uploadStudent(@RequestParam("file") MultipartFile multipartFile, String uid, @SessionAttribute("user") User user) throws IOException {
        InputStream inputStream = multipartFile.getInputStream();
        int result = studentInfoService.upload(inputStream, uid, user);
        if (result == 0){
            return Result.success("文件上传成功!");
        }else {
            return Result.error("文件上传失败，在" + result + "行,请检查是否正确输入,只能包含中文、英文、数字");
        }
    }

    @ApiOperation("重置学生密码")
    @PostMapping("/reset/{id}/{stuid}")
    public Result resetPassword(@ApiParam("学生id") @PathVariable("id") Integer id,
                                @ApiParam("学生学号") @PathVariable("stuid") String stuid){
        studentInfoService.resetPassword(id, stuid);
        return Result.success("重置成功!");
    }

    @ApiOperation("通过cid查询班级所在学生")
    @GetMapping("/get/{username}")
    public Result selectStudentInfoByCid(@ApiParam(name = "username", value = "老师工号", required = true)
                                         @PathVariable("username") String username,
                                         @RequestParam String cid){
        // 查询学生前判断是否有考勤记录 有考勤记录就联合记录表 将 考勤详情查出来 没有就默认状态为1
        Schedule schedule = scheduleService.selectScheduleByCidAndDate(username, cid);
        Integer attId = attendanceService.selectAttendanceByScheduleId(schedule.getId() + "");
        List<StudentAttendanceRecord> studentInfoList;
        Result result = new Result();
        Map<String, Object> data = new HashMap<>();
        if (attId == null || attId <= 0){
            studentInfoList = studentInfoService.selectStudentInfoByCid(schedule.getId() + "", cid);
            data.put("studentInfoList", studentInfoList);
            data.put("attId", 0);
        }else {
            studentInfoList = attendanceService.selectStudentByAttId(attId + "");
            data.put("studentInfoList", studentInfoList);
            data.put("attId", attId);
        }
        result.setData(data);
        return result;
    }

    @ApiOperation("查询考勤统计")
    @GetMapping("/selectBystuSum")
    public Result selectBystuSum( @RequestParam("stuid") String[] stuid){
        List<Map<String,Object>> list =new ArrayList<>();
        for (int i = 0; i < stuid.length; i++) {
          Map<String, Object> map = studentInfoService.selectBystuSum(stuid[i]);
          list.add(map);
        }
        return Result.success(list);
    }

    @ApiOperation("查询考勤统计")
    @GetMapping("/selectBystuInfoSum")
    public Result selectBystuInfoSum( @RequestParam("pageSize") int pageSize,@RequestParam("pageNum") int pageNum,@RequestParam("cname") String cname){
        Map<String, Object> map = studentInfoService.selectBystuInfoSum(pageNum, pageSize, cname);
        return Result.success(map);
    }

}
